/**
 * 2017年11月24日
 */
package com.alibaba.study.anno;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Alex
 *
 */

public class Driver {
	public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
		Person p = new Person("abc", "def,","no");
	
		System.out.println(getSql(p));
	}
	static String getSql(Object o) throws IllegalArgumentException, IllegalAccessException{
		String sql = "update table %s set ";
		String tableName = "";
		Map<String,String> map  = new HashMap<>();
		Class<?> clz = o.getClass();
		if(clz.isAnnotationPresent(Table.class)){
			Table t = clz.getAnnotation(Table.class);
			tableName = t.name();
			Field [] fields = clz.getDeclaredFields();
			for(Field f:fields){
				if(f.isAnnotationPresent(DBField.class)){
					f.setAccessible(true);
					String val = (String)f.get(o);
				
					DBField dbf = f.getAnnotation(DBField.class);
					String dbCol = dbf.name();
					dbCol = dbCol.length()== 0?f.getName():dbCol;
					map.put(dbCol,val);			
				}
			}
		}
		String ts = String.format(sql, tableName);
		for(String key:map.keySet()){
			ts += " "+ key;
			ts += " = ";
			ts += map.get(key);
		}
		return ts;
	}
}
